﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DSS_XNA.Engine.Error;
using System.Xml;
using System.Reflection;

namespace DSS_XNA.Engine.Actor
{
    public static class Actor
    {
        #region Public Static Methods

        public static IActor Create(string fileName, Game1 engine)
        {
            if (fileName == null)
                throw new DSSException("'fileName' is null.");

            fileName = String.Format("actors\\{0}.atr", fileName);
            fileName = Util.Util.GetFullPath(fileName);

            XmlDocument doc = new XmlDocument();
            doc.Load(fileName);

            string texture = doc.SelectSingleNode("actor/texture").InnerText;
            string className = doc.SelectSingleNode("actor/className").InnerText;
            float width = (float)Convert.ToDouble(doc.SelectSingleNode("actor/width").InnerText);
            float height = (float)Convert.ToDouble(doc.SelectSingleNode("actor/height").InnerText);

            Assembly asm = Assembly.GetCallingAssembly();
            Type type = asm.GetType(className);
            if (type == null)
                throw new DSSException(String.Format("Failed to find the actor class: {0}",
                    className));

            ConstructorInfo con = type.GetConstructor(new Type[] { });

            IActor actor = con.Invoke(new object[] { }) as IActor;
            if (actor == null)
                throw new DSSException("'actor' is null.");

            texture = String.Format("actors/sprites/{0}", texture);
            texture = Util.Util.GetFullPath(texture);

            actor.Load(doc, engine, texture, width, height);

            return actor;
        }

        #endregion
    }
}
